
#include "messagecontentlabel.h"
#include "model/datacenter.h"

MessageContentLabel::MessageContentLabel(model::MessageType type, const QString &text, const QString &fileId, const QByteArray &content, bool isLeft)
    :messageType(type),fileId(fileId), content(content), isLeft(isLeft),fileName("")
{
    //设置延展模式
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    label = new QLabel(this);//这里必须写this,将label挂载到qwidget上!!!

    //设置字体样式
    QFont font;
    font.setFamily("微软雅黑");
    font.setPixelSize(16);

    label->setText(text);
    label->setFont(font);
    label->setAlignment(Qt::AlignLeft | Qt:: AlignVCenter);
    label->setWordWrap(true);
    label->setStyleSheet("QLabel { padding: 0 10px; line-height: 1.2;}");

    if(type == model::MessageType::TEXT_TYPE) return;

    this->fileName = text;

    if(this->content.isEmpty())
    {
        //通过网络加载数据
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        connect(dataCenter,&model::DataCenter::getSingleFileDone,this,&MessageContentLabel::updateUI);
        dataCenter->getSingleFileAsync(fileId);
    }
    else
    {
        //本地数据, 直接修改loadContentDone
        this->loadContentDone = true;
    }
}


void MessageContentLabel::paintEvent(QPaintEvent *event)
{
    QObject* object = this->parent();

    if(!object->isWidgetType())
    {
        LOG() << "void MessageContentLabel::paintEvent(QPaintEvent *event) 失败, 父元素不为QWidget类型";
        return;
    }

    //确实为widget, 进行类型转换
    QWidget* parent = dynamic_cast<QWidget*>(object);

    //文字泡宽度为父元素60%
    int originalWidth = parent->width() * 0.6;

    //创建QFontMetrics类对象
    QFontMetrics fontMetrics(label->font());

    //获取文本长度
    int textWidth = fontMetrics.horizontalAdvance(label->text());

    //计算行数, 40为调整值, 为了防止消息太长过于贴近消息展示区边框
    int row = textWidth/(originalWidth - 40) + 1;

    //计算实际显示的文字泡宽度, 如果文本长度 + 补正值仍为达到父元素最大宽度60%, 就将实际显示的文字泡宽度 改为该值, 否则为父元素最大宽度60%
    int width = textWidth + 40 >= originalWidth ? originalWidth : textWidth + 40;

    //计算高度
    int height = row * (label->font().pixelSize() * 1.2) + 20;//字体本身大小 * 行间距 + 上下留白

    //绘图API
    QPainter painter(this);
    //设置抗锯齿
    painter.setRenderHint(QPainter::Antialiasing);

    //QPainterPath类为绘制操作提供了一个容器，允许构造和重用图形形状
    QPainterPath path;
    if(isLeft)
    {
        painter.setPen(QColor(247,247,247));
        painter.setBrush(QBrush(QColor(253,253,253)));

        //绘制圆角矩形
        path.addRoundedRect(10,0,width,height,10,10);

        //绘制三角形
        path.moveTo(0,15);
        path.lineTo(10,5);
        path.lineTo(10,25);
        path.closeSubpath();

        painter.drawPath(path);

        //移动label到文字泡上
        label->setGeometry(10,0,width,height);
    }
    else
    {
        painter.setPen(QColor(149,236,105));
        painter.setBrush(QBrush(QColor(149,236,105)));

        //绘制圆角矩形
        int leftPos = this->width()- width - 10;
        int rightPos = this->width() - 10;
        path.addRoundedRect(leftPos,0,width,height,10,10);

        //绘制三角形
        path.moveTo(rightPos + 10,15);
        path.lineTo(rightPos, 5);
        path.lineTo(rightPos, 25);
        path.closeSubpath();

        painter.drawPath(path);
        label->setGeometry(leftPos,0,width,height);
    }

    parent->setFixedHeight(height + 50); //height为当前文字泡高度, 30则是为头像和名称时间预留的空间

}

void MessageContentLabel::mousePressEvent(QMouseEvent *event)
{
    // 是鼠标左键点击
    if(event->button() == Qt::LeftButton)
    {
        // 如果为文件类型
        if(messageType == model::MessageType::FILE_TYPE)
        {
            //如果数据尚未加载完毕
            if(!loadContentDone)
            {
                LOG() << "数据尚未加载完毕";
                Toast::showMessage("网络数据尚未加载完毕, 请稍后再试...");
                return;
            }
            else
            {
                saveAsFile(this->content);
            }
        }

        // 如果为语音类型
        if(messageType == model::MessageType::SPEECH_TYPE)
        {
            //如果数据尚未加载完毕
            if(!loadContentDone)
            {
                LOG() << "数据尚未加载完毕";
                Toast::showMessage("网络数据尚未加载完毕, 请稍后再试...");
                return;
            }
            else
            {
                label->setText("播放中...");
                SoundRecorder* soundRecorder = SoundRecorder::getInstance();
                connect(soundRecorder,&SoundRecorder::soundPlayDone,this,&MessageContentLabel::soundPlayDone,Qt::UniqueConnection);
                soundRecorder->startPlay(content);
            }


        }
    }





}

void MessageContentLabel::updateUI(const QString& fileId, const QByteArray& content)
{
    if(fileId != this->fileId)  return;
    this->content = content;
    this->loadContentDone = true;
    this->update();
}

void MessageContentLabel::saveAsFile(const QByteArray &content)
{
    QString filePath = QFileDialog::getSaveFileName(this,"另存为",QDir::homePath(),"files (*)");
    if (filePath.isEmpty()) {
        LOG() << "用户取消了文件另存为";
        return;
    }
    model::writeByteArrayToFile(filePath,content);
}

void MessageContentLabel::soundPlayDone()
{
    if(label->text() == "播放中...") label->setText("[语音]");
}

void MessageContentLabel::contextMenuEvent(QContextMenuEvent *event)
{
    // 如果为语音类型
    if(messageType == model::MessageType::SPEECH_TYPE)
    {
        QMenu* menu = new QMenu(this);
        QAction* action = menu->addAction("语音转文字");

        connect(action,&QAction::triggered,this,[=](){
            model::DataCenter* dataCenter = model::DataCenter::getInstance();
            connect(dataCenter,&model::DataCenter::speechConvertTextDone,this,&MessageContentLabel::speechConvertTextDone);
            dataCenter->speechConvertTextAsync(this->fileId,this->content);
        });

        menu->exec(event->globalPos());
        delete menu;
    }
}

void MessageContentLabel::speechConvertTextDone(const QString &fileId, const QString &text)
{
    if(fileId != this->fileId)
    {
        return;
    }

    label->setText(text);

    this->update();
}




























